import { NextRequest, NextResponse } from 'next/server';
import prisma from '@/lib/db';
import {TaskHourTableItem } from '@/types/Model';
import moment from 'moment';
export const dynamic = 'force-dynamic'; // 强制动态渲染

export const GET = async (req: NextRequest) => {
  try {
    const { searchParams } = new URL(req.url);
    // const user_id = searchParams.get('user_id');
    // const start_date = searchParams.get('start_date');
    // const end_date = searchParams.get('end_date');

    const productsWithHierarchy = await prisma.product.findMany({
      include: {
        userstories: {
          include: {
            tasks: {
              where: {
                status: "Done" 
              },
              include:{
                member:true,
              }
            },
            sprint_user_stories:{
              include:{
                sprint:true
              }
            }
          }
        }
      }
    });
    // console.log(productsWithHierarchy[0])

    const tableData: TaskHourTableItem[] = productsWithHierarchy.flatMap((product) => 
      product.userstories?.flatMap((userStory) => 
        userStory.tasks?.map((task) => ({
          product_id:product.id,
          product: product.name,
          feature_id:userStory.feature_id,
          user_story: userStory.name,
          sprint_id:task.sprint_id,
          task: task.name,
          hours: task.hours,  
          note: task.description,  
          create_time: task.create_time,  
          user_id: task.member_id,
          user_name:task.member?.name
        } as TaskHourTableItem)) ?? []
      ) ?? []
    );

    return NextResponse.json(tableData);
  } catch (error) {
    console.error('Failed to fetch product hierarchy:', error);
    return NextResponse.json(
      { 
        error: 'Failed to fetch product hierarchy',
        details: error instanceof Error ? error.message : 'Unknown error'
      },
      { status: 500 }
    );
  }
}
